package com.lc.app.myaccount.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.lc.app.myaccount.entity.InAccount;
import com.lc.app.myaccount.entity.OutAccount;
import com.lc.app.myaccount.helper.DBOpenHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by LC on 2/5/2016.
 */
public class OutAccountDao {
    private DBOpenHelper helper;
    private SQLiteDatabase db;

    public OutAccountDao(Context context) {
        this.helper = new DBOpenHelper(context);
        db = helper.getWritableDatabase();
    }

    public void add(OutAccount outAccount) {
        db.execSQL("insert into tb_out_account (money,time,type,address,mark,user_id) values(?,?,?,?,?,?)", outAccount.toAddArray());
    }

    public void update(OutAccount outAccount) {
        db.execSQL("update tb_out_account set money=?,time=?,type=?,address=?,mark=?,user_id = ? where _id = ?", outAccount.toUpdateArray());
    }

    public OutAccount find(int id) {
        Cursor cursor = db.rawQuery("select _id,money,time,type,address,mark,user_id from tb_out_account where _id = ?", new String[]{String.valueOf(id)});
        if (cursor.moveToNext()) {
            OutAccount outAccount = new OutAccount();
            outAccount.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
            outAccount.setMoney(cursor.getDouble(cursor.getColumnIndex("money")));
            outAccount.setTime(cursor.getString(cursor.getColumnIndex("time")));
            outAccount.setType(cursor.getString(cursor.getColumnIndex("type")));
            outAccount.setAddress(cursor.getString(cursor.getColumnIndex("address")));
            outAccount.setMark(cursor.getString(cursor.getColumnIndex("mark")));
            outAccount.setUserId(cursor.getInt(cursor.getColumnIndex("user_id")));

            return outAccount;
        } else {
            return null;
        }
    }

    public List<OutAccount> findByUserId(int userId) {
        Cursor cursor = db.rawQuery("select _id,money,time,type,address,mark,user_id from tb_out_account where user_id = ?", new String[]{String.valueOf(userId)});
        List<OutAccount> list = new ArrayList<OutAccount>();
        while (cursor.moveToNext()) {
            OutAccount outAccount = new OutAccount();
            outAccount.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
            outAccount.setMoney(cursor.getDouble(cursor.getColumnIndex("money")));
            outAccount.setTime(cursor.getString(cursor.getColumnIndex("time")));
            outAccount.setType(cursor.getString(cursor.getColumnIndex("type")));
            outAccount.setAddress(cursor.getString(cursor.getColumnIndex("address")));
            outAccount.setMark(cursor.getString(cursor.getColumnIndex("mark")));
            outAccount.setUserId(cursor.getInt(cursor.getColumnIndex("user_id")));

            list.add(outAccount);
        }

        return list;
    }
}
